package com.group02.community.listen;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.group02.community.entity.user.SysUser;
import com.group02.community.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class DataListener extends AnalysisEventListener<SysUser> {

    private static final int BATCH_COUNT = 50;
    List<SysUser> sysUserList = new ArrayList<SysUser>();
    private IUserService userService;

    public DataListener(IUserService userService) {
        this.userService = userService;
    }

    // 每一行都会调用
    @Override
    public void invoke(SysUser sysUser, AnalysisContext analysisContext) {
        sysUserList.add(sysUser);
        if (sysUserList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            sysUserList.clear();
        }
    }

    // 解析完成
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if(sysUserList.size()==0){
            return;
        }
        saveData();
        log.info("读取完成");
    }

    public void saveData() {
        userService.emptyDatabase();
        userService.saveBatch(sysUserList); //代码实现类层保存数据
        log.info("存储数据库成功！");
    }
}